package com.dreamchaser.depository_manage.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 验证码生成与校验工具类
 * 使用Hutool API
 * @author yancy0109
 */
public class CodeUntils {

    // 优化 ----> 使用redis作为缓存
    private static Map<String, LineCaptcha> codeMap = new ConcurrentHashMap<>(10);

    /**
     * 根据SessonId分配验证码
     * @param request
     * @return
     */
   public static String getImageBase64(HttpServletRequest request){
       String sessionId = request.getSession().getId();
//       System.out.println("getSessionId : get64 : "+sessionId);
       removeCode(sessionId);
       // 为当前SessionId分配Code ---> Base64
       //定义图形验证码的长和宽
       LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(110, 31, 4, 20);
       String imageBase64 = lineCaptcha.getImageBase64();
       codeMap.put(sessionId, lineCaptcha);
       return imageBase64;
   }

    // 移除Code缓存
    private static void removeCode(String sessionId) {
        // 如果存储了当前SessionId相关验证码对象, 先移除
        if (codeMap.containsKey(sessionId)) {
            codeMap.remove(sessionId);
        }
    }

    public static boolean checkImageBase64(HttpServletRequest request, String userCode){
        String sessionId = request.getSession().getId();
//        System.out.println("getSessionId : check64 : "+sessionId);
        if (!codeMap.containsKey(sessionId)) {
            return false;
        }
        // 存在, 则进行验证
        LineCaptcha lineCaptcha = codeMap.get(sessionId);
//        System.out.println("user : " + userCode + "   : system : " + lineCaptcha.getCode());
        boolean verifyResult = lineCaptcha.verify(userCode);
        // 如果检验失败, 移除Map中验证码
        if (!verifyResult) {
            removeCode(sessionId);
        }
        return verifyResult;
    }
}
